from django.core.paginator import Paginator
from django.http import QueryDict
from django.shortcuts import render, reverse
from django.views import View
from . import models
# from course.models import Course
from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from utils.res_code import json_response, Code

from django.http import HttpResponse


from .models import Menu
from .forms import MenuModelForm, UserModelForm ,GroupModelForm,CateModelForm
from user.models import User
from course.models import Course,CourseCategory,CourseLesson,CourseBag,CourseCategoryType
from django.contrib.auth.mixins import PermissionRequiredMixin
from .generic import MyListView, UpdateView, AddView
# from django.contrib.auth.decorators import login_required
# @login_required
# def homepage(request):
#     pass


class MyPermissionRequiredMixin(PermissionRequiredMixin):
    def has_permission(self):
        """
        覆盖父类方法，解决一个视图内不同请求，权限不同的问题
        :return:
        """
        perms = self.get_permission_required()
        if isinstance(perms, dict):
            if self.request.method.lower() in perms:
                return self.request.user.has_perms(perms[self.request.method.lower()])
        else:
            return self.request.user.has_perms(perms)

    def handle_no_permission(self):
        """
        覆盖父类方法，解决没有权限ajax请求返回json数的问题
        :return:
        """
        if self.request.is_ajax():
            # 没有权限是有两种情况
            # 1. 登陆了但是确实没有权限
            if self.request.user.is_authenticated:
                return json_response(errno=Code.ROLEERR, errmsg='您没有权限！')
            else:
                # 2. 没有登录
                return json_response(errno=Code.SESSIONERR, errmsg='您未登录，请登录！', data={'url': reverse(self.get_login_url())})
        else:
            return super().handle_no_permission()



class IndexView(View):
    def get(self, request):
        # menus = [
        #     {
        #         "name": "工作台",
        #         "url": "myadmin:home",
        #         "icon": "fa-link"
        #     },
        #
        #     {
        #         "name": "课件审核",
        #         "icon": "fa-link",
        #         "children": [
        #             {
        #                 "name": "审核课件资料",
        #                 "url": "myadmin:course_list"
        #             },
        #             {
        #                 "name": "测试删除",
        #                 "url": "myadmin:course_manage"
        #             },
        #             {
        #                 "name": "整理课件包",
        #                 "url": "myadmin:course_bag"
        #             },
        #
        #     ]
        #     },
        #     {
        #         "name": "账号管理",
        #         "icon": "fa-link",
        #         "children": [
        #             {
        #                 "name": "权限分组",
        #                 "url": "myadmin:group_list"
        #             },
        #             # {
        #             #     "name": "管理员账号注册",
        #             #     "url": "myadmin:wait"
        #             # },
        #             {
        #                 "name": "账号管理",
        #                 "url": "myadmin:user_list"
        #             }, {
        #                 "name": "菜单管理",
        #                 "url": "myadmin:menu_list"
        #             },
        #         ]
        #     }
        #
        # ]
        # 1. 拿到所有的可用，可见菜单，一级菜单
        # 1. 拿到所有的可用，可见菜单，一级菜单
        objs = Menu.objects.only('name', 'url', 'icon', 'permission__codename',
                                 'permission__content_type__app_label').select_related(
            'permission__content_type').filter(is_visible=True, parent=None)
        # 2. 过滤用户拥有权限的菜单
        has_permissions = request.user.get_all_permissions()
        # 3. 构造数据结构
        menus = []
        for menu in objs:
            if '%s.%s' % (menu.permission.content_type.app_label, menu.permission.codename) in has_permissions:
                temp = {
                    'name': menu.name,
                    'icon': menu.icon
                }
                # 检查是否有可用，可见的子菜单
                children = menu.children.filter(is_visible=True)
                if children:
                    temp['children'] = []
                    for child in children:
                        if '%s.%s' % (
                        child.permission.content_type.app_label, child.permission.codename) in has_permissions:
                            temp['children'].append({
                                'name': child.name,
                                'url': child.url
                            })
                else:
                    if not menu.url:
                        continue
                    temp['url'] = menu.url

                menus.append(temp)

        return render(request, 'myadmin/index.html', context={'menus': menus})
# Create your views here.
class HomeView(View):
    def get(self, request):
        return render(request, 'myadmin/home.html')


class WaitView(View):
    def get(self, request):
        return render(request, 'myadmin/wait.html')
class MenuListView(View):
    """
    菜单列表视图
    url:/admin/menus/
    """

    def get(self, request):
        menus = models.Menu.objects.only('name', 'url', 'icon', 'is_visible', 'order', 'codename').filter(parent=None)
        return render(request, 'myadmin/menu/menu_list.html', context={'menus': menus})


class MenuAddView(View):
    """
    添加菜单视图
    url:/admin/menu/
    """

    def get(self, request):
        form = MenuModelForm()
        return render(request, 'myadmin/menu/add_menu.html', context={'form': form})

    def post(self, request):
        # 1. 接受参数并验证
        form = MenuModelForm(request.POST)
        if form.is_valid():
            # 创建菜单
            new_menu = form.save()
            # 菜单的权限对象
            content_type = ContentType.objects.filter(app_label='myadmin', model='menu').first()
            permission = Permission.objects.create(name=new_menu.name, content_type=content_type,
                                                   codename=new_menu.codename)
            new_menu.permission = permission
            new_menu.save(update_fields=['permission'])

            return json_response(errmsg='菜单添加成功！')
        else:
            return render(request, 'myadmin/menu/add_menu.html', context={'form': form})

class MenuUpdateView(MyPermissionRequiredMixin,View):
    """
    菜单管理视图
    url:/admin/menu/<int:menu_id>/
    """
    permission_required = {
        'get': ('myadmin.menu_update',),
        'put': ('myadmin.menu_update',),
        'delete': ('myadmin.menu_delete',)
    }
    def delete(self, request, menu_id):
        menu = Menu.objects.filter(id=menu_id).only('name')
        if menu:
            menu = menu[0]
            if menu.children.filter().exists():
                return json_response(errno=Code.DATAERR, errmsg='父菜单不能删除！')
            menu.permission.delete()
            menu.delete()
            return json_response(errmsg='删除菜单：%s成功' % menu.name)
        else:
            return json_response(errno=Code.NODATA, errmsg='菜单不存在！')

    def get(self, request, menu_id):
        menu = Menu.objects.filter(id=menu_id).first()
        form = MenuModelForm(instance=menu)

        return render(request,"myadmin/menu/updata_menu.html", context={"form": form})

    def put(self, request, menu_id):
        menu = models.Menu.objects.filter(id=menu_id).first()
        put_data = QueryDict(request.body)
        form = MenuModelForm(put_data, instance=menu)
        if form.is_valid():
            obj = form.save()
            flag = False
            if 'name' in form.changed_data:
                obj.permission.name = obj.name
                flag = True
            if 'codename' in form.changed_data:
                obj.permission.codename = obj.name
                flag = True
            if flag:
                obj.permission.save()
            return json_response(errmsg='菜单修改成功！')
        else:
            return render(request, 'myadmin/menu/update_menu.html', context={'form': form})

class UserUpdateView(View):
    """
    用户更新视图
    url:/admin/user/<int:user_id>
    """
    def get(self, request, user_id):
        user = User.objects.filter(id=user_id).first()
        if user:
            form = UserModelForm(instance=user)
        else:
            form = UserModelForm()
        return render(request, 'myadmin/menu/user_detail.html', context={'form': form})

    def put(self, request, user_id):
        user = User.objects.filter(id=user_id).first()
        put = QueryDict(request.body)
        if user:
            form = UserModelForm(put, instance=user)
        else:
            form = UserModelForm()
        if form.is_valid():
            form.save()
            return json_response(errmsg="用户修改成功")
        else:
            return render(request, 'myadmin/menu/user_detail.html', context={'form': form})

class UserListView(View):
    def get(self,request):
        user_queryset = User.objects.only("username", "is_active", "mobile", "is_staff", "is_superuser",'w')
        groups = Group.objects.only("name")
        groups__id = request.GET.get("group")
        quert_dict = {}
        if groups__id:
            try:
                groups__id = int(groups__id)
                quert_dict["groups__id"] = groups__id
            except Exception as e:
                pass
        is_staff = request.GET.get("is_staff")
        if is_staff =="0":
            quert_dict["is_staff"] =False
        if is_staff == "1":
            quert_dict["is_staff"] = True
        is_superuser = request.GET.get("is_superuser")
        if is_superuser == "0":
            quert_dict["is_superuser"] = False
        if is_superuser == "1":
            quert_dict["is_superuser"] = True
        username = request.GET.get("username")
        if username:
            quert_dict["username"] = username
        try:
            page = int(request.GET.get("page", 1))
        except Exception as e:
            page=1
        paginator = Paginator(user_queryset.filter(**quert_dict), 1000)
        users =paginator.get_page(page)
        context = {
            "users": users,
            "groups": groups,
        }
        context.update(quert_dict)
        return render(request, 'myadmin/user_list.html', context=context)


class GroupListView(View):
    """
    url:myadmin/groups
    """
    def get(self, request):
        groups = Group.objects.only("name").all()
        return render(request, "myadmin/group/group_list.html", context={"groups": groups})

class GroupDelView(View):


    def delete(self,request,id):
        # id = request.GET.get('courseId')
        id = Group.objects.filter(id=id)
        if id:
            print(id)
            id.delete()
        return json_response(errmsg="分组删除成功")






class GroupUpdateView(View):
    """
    url:admin/group/<int:group_id>
    """
    def get(self, request, group_id):
        group = Group.objects.filter(id=group_id).first()

        if not group:
            return json_response(errno=Code.NODATA, errmsg="没有此分组")
        form = GroupModelForm(instance=group)
        menus = Menu.objects.only('name', 'permission_id').select_related('permission').filter(parent=None)
        permissions = group.permissions.only('id').all()

        return render(request, "myadmin/group/group_detail.html", context={
            'form': form,
            'menus': menus,
            'permissions': permissions
        })

    def put(self, request, group_id):
        # 1. 拿到要修改的分组
        group = Group.objects.filter(id=group_id).first()
        # 1.1 判断是否存不存在
        # 1.1 判断是否存不存在
        if not group:
            return json_response(errno=Code.NODATA, errmsg='没有此分组！')
        # 2. 拿到前端传递的参数
        put_data = QueryDict(request.body)
        # 3. 校验参数
        # 3.1 创建表单对象
        form = GroupModelForm(put_data, instance=group)
        if form.is_valid():
            # 4. 如果成功，保存数据
            form.save()
            return json_response(errmsg='修改分组成功！')
        else:
            # 5. 如果失败
            menus = Menu.objects.only('name', 'permission_id').select_related('permission').filter(parent=None)
            # 4.拿到当前组的可用权限
            permissions = group.permissions.only('id').all()
            return render(request, 'myadmin/group/group_detail.html', context={
                'form': form,
                'menus': menus,
                'permissions': permissions
            })




class GroupAddView(View):
    """
    添加分组视图
    url: /admin/group/
    """
    def get(self, request):
        # 1. 创建一个空表单
        form = GroupModelForm()
        # 2. 拿到所有的可用一级菜单
        menus = Menu.objects.only('name', 'permission_id').select_related('permission').filter(parent=None)
        # 3. 返回渲染表单
        return render(request, 'myadmin/group/group_detail.html', context={
            'form': form,
            'menus': menus
        })

    def post(self, request):
        # 1.根据post的数据，创建模型表单对象
        form = GroupModelForm(request.POST)
        # 2.校验
        if form.is_valid():
            # 3.如果成功，保存，返回ok
            form.save()
            return json_response(errmsg='添加分组成功！')
        else:
            # 4.如果失败，返回渲染了错误信息的表单html
            menus = Menu.objects.only('name', 'permission_id').select_related('permission').filter(parent=None)
            return render(request, 'myadmin/group/group_detail.html', context={
                'form': form,
                'menus': menus
            })


class CourseCateTypeList(MyListView):

    model = CourseCategoryType
    page_header = '课程类别'
    page_option = '课程类别'
    table_title = '课程类别'

    fields = ['name','title']

class CourseCateTypeAdd(AddView):
    """
    课程类添加
    """
    # permission_required = ('myadmin.course_add',)
    model = CourseCategoryType
    page_header = '课程类别'
    page_option = '课程类别添加'
    table_title = '课程类别添加'
    fields = ['name']


class CourseCateTypeUpdate(UpdateView):
    # permission_required = ('myadmin.course_add',)
    model = CourseCategoryType
    page_header = '课程类别修改'
    page_option = '课程类别修改'
    table_title = '课程类别修改'
    fields = ['name']


class CourseCateTypeDel(View):
    """
    课程类删除
    """
    def delete(self,request,id):
        aa = CourseCategoryType.objects.filter(id=id).first()
        if aa:
            print(aa)
            aa.delete()
        return json_response(errmsg="删除成功")


class CourseCateList(View):
    """
    课程列表
    """
    def get(self,request,category_type_id):
        category = CourseCategory.objects.filter(category_type_id=category_type_id)
        return render(request,'myadmin/coursecategory/coursecategory_list.html',context={
            'category':category
        })



# class CourseCateAdd(AddView):


class CourseCateAdd(View):
    def get(self, request):
        form = CateModelForm()
        return render(request, 'myadmin/coursecategorytype/add_category.html', context={'form': form})

    def post(self, request):
            # 1. 接受参数并验证
        form = CateModelForm(request.POST)
        if form.is_valid():
                # 创建菜单
            new_menu = form.save()
                # 菜单的权限对象
            # content_type = ContentType.objects.filter(app_label='myadmin', model='menu').first()
            # permission = Permission.objects.create(name=new_menu.name, content_type=content_type,
            #                                            codename=new_menu.codename)
            # new_menu.permission = permission
            new_menu.save()

            return json_response(errmsg='课程添加成功！')
        else:
            return render(request, 'myadmin/coursecategorytype/add_category.html', context={'form': form})
    # permission_required = ('myadmin.course_add',)
    # model = CourseCategory
    # page_header = '课程管理'
    # page_option = '课程添加'
    # table_title = '课程添加'
    # fields = ['name','category_type']


# class CourseCateUpdate(UpdateView):
class CourseCateUpdate(View):
    """
    课程编辑
    """
    def get(self, request, menu_id):
        cate = CourseCategory.objects.filter(id=menu_id).first()
        form = CateModelForm(instance=cate)

        return render(request,"myadmin/coursecategorytype/updata_categorylist.html", context={"form": form})

    def put(self, request, menu_id):
        menu = CourseCategory.objects.filter(id=menu_id).first()
        put_data = QueryDict(request.body)
        form = CateModelForm(put_data, instance=menu)
        if form.is_valid():
            obj = form.save()
            flag = False
            if 'name' in form.changed_data:

                flag = True
            if 'codename' in form.changed_data:

                flag = True
            if flag:
                return json_response(errmsg='菜单修改成功！')
            else:
                return json_response(errmsg='没有修改')
        else:
            return render(request, 'myadmin/coursecategorytype/updata_categorylist.html', context={'form': form})
#     # permission_required = ('myadmin.course_add',)
#     model = CourseCategory
#     page_header = '课程名修改'
#     page_option = '课程名修改'
#     table_title = '课程名修改'
#     fields = ['name']

class CousreCateDel(View):
    """
    课程删除
    """
    def delete(self,request,id):
        cate = CourseCategory.objects.filter(id=id)
        if cate:
            cate.delete()
            return json_response(errmsg="删除成功")


class CourseCateDetail(View):
    def get(self,request,category_id,**kwargs):
        lesson=CourseLesson.objects.filter(category_id=category_id)


        return render(request,'myadmin/coursecategory/1.html',context={
            'lesson':lesson
        })


class CourseLessonUpdate(UpdateView):
    # permission_required = ('myadmin.course_add',)
    model = CourseLesson
    page_header = '课件管理'
    page_option = '课件添加'
    table_title = '课件添加'
    fields = ['name','category']


class CourseLessonAdd(AddView):
    # permission_required = ('myadmin.course_add',)
    model = CourseLesson
    page_header = '课件管理'
    page_option = '课件添加'
    table_title = '课件添加'
    fields = ['name','category']


class Courselesson(View):
    def get(self,request,category_id):
        course = Course.objects.values('lesson__name','title','teacher__name','update_time').filter(category_id=category_id,).distinct()
        lesson = Course.objects.only('lesson__name').filter().distinct()
        print(course)
        print(lesson)


        return render(request,'myadmin/course/course_lesson.html',context={
            'course':course,
            'category_id':category_id,
            'lesson':lesson,
        })



class CourseLessonDetail(View):
    def get(self,request):
        courses = Course.objects.only('title', 'cover_url', 'teacher__name', 'teacher__title', 'category','lesson').select_related('teacher').filter(is_delete=False)
        return render(request,'myadmin/course/course_lessondetail.html',context={
            'courses': courses,
        })



# class CourseListView(MyListView):
#     permission_required = ('myadmin.course_list',)
#     model = Course
#     page_header = '在线课堂'
#     page_option = '课程管理'
#     table_title = '课程列表'
#
#     fields = ['title','lesson', 'category__name', 'teacher__name', 'profile', 'outline', 'duration', 'cover_url', 'is_delete','is_pass']


class CourseListView(View):
    def get(self,request):
        course1=Course.objects.all().order_by('title')
        category=CourseCategory.objects.all().filter(parent_id__isnull=False).order_by('name')
        categorytype=CourseCategory.objects.all().filter(parent_id=None)
        quert_dict = {}
        cate = request.GET.get('haha')
        catetype = request.GET.get('hehe')

        print(catetype)
        if cate:
            quert_dict['category_id'] = cate

        else:
            pass
        if catetype:
            quert_dict['category_id__parent_id'] = catetype
        else:
            pass
        print(quert_dict)
        course= course1.filter(**quert_dict)
        print(course)
        context={
            "course": course,
            "category": category,
        }
        context.update(quert_dict)

        # context.update(quert_dict)



        return render(request,'myadmin/course/course_list.html',context={
            'course':course,
            "category":category,
            'categorytype':categorytype

        })



class CourseUpdateView(UpdateView):
    permission_required = ('myadmin.course_update',)
    model = Course
    page_header = '课件管理'
    page_option = '课件管理'
    table_title = '课件管理'

    fields = ['title','lesson','is_example','is_outline','category']

# class LessonAdd(View):
#     def post(self,request):
#         lesson_name = request.POST.get('lesson_name')
#         print(lesson_name)
#         lesson = CourseLesson(name=lesson_name)
#         lesson.save()
#         return json_response(errmsg="课程添加成功")



class CourseLessonView(View):
    def get(self,request):
        courses=Course.objects.only('title','video_url','lesson_id').filter(is_delete=False,is_pass=0)
        example = Course.objects.only('title', 'video_url').filter(is_delete=False, is_example=True,is_pass=0)
        outline = Course.objects.only('title', 'video_url').filter(is_delete=False, is_outline=True,is_pass=0)

        query_dict={}
        lesson_aa=request.GET.get('lesson_name')
        print(lesson_aa)

        lesson_dd = CourseLesson.objects.only('id').filter(name=lesson_aa).last()



        if lesson_dd:
            query_dict['lesson_id']=lesson_dd.id
            print(query_dict)
        else:
            pass





        course=courses.filter(**query_dict)
        examples=example.filter(**query_dict)
        outlines=outline.filter(**query_dict)



        context = {
            'courses': courses,
            'example': example,
            'outline': outline,
            # 'category':category,
        }
        # print(context)
        context.update(query_dict)

        return render(request, 'myadmin/course/courses_pub.html',context={
            'course': course,
            'examples': examples,
            'outlines': outlines,
            # 'category':category,

        })

    def post(self, request):
        lesson_name=request.POST.get('lesson_name')
        print(lesson_name)
        title = request.POST.get('title')
        cover_url = request.POST.get('cover_url')
        video_url = request.POST.get('video_url')
        video = Course(title=title, cover_url=cover_url, video_url=video_url)
        lesson=CourseLesson(name=lesson_name)
        lesson.save()
        video.save()

        print(video)
        # if form.is_valid():
        return json_response(errmsg="课程添加成功")



class CourseAddView(View):


    def get(self,request):
        courses=Course.objects.only('title','video_url','lesson').filter(is_delete=False)
        example=Course.objects.only('title','video_url').filter(is_delete=False,is_example=True)
        outline=Course.objects.only('title','video_url').filter(is_delete=False,is_outline=True)
        lesson= Course.objects.values('lesson__name').filter(is_delete=False).distinct()


        return render(request,'myadmin/course/courses_pub.html',context={
            'courses':courses,
            'example':example,
            'outline':outline,
            'lesson':lesson,
        })
    def delete(self,request,course_id):
        course = Course.objects.only('id').filter(is_delete=False, id=course_id).first()
        # course.update(is_delete=True)
        if course:
            # course.is_delete = True
            # course.save(update_fields=['is_delete'])
            course.delete()
            return json_response(errmsg='课程删除成功')
        else:
            return json_response(errno=Code.PARAMERR, errmsg='更新的课程不存在')

class CourseAddView1(View):
    def post(self,request):
        title=request.POST.get('title')
        cover_url=request.POST.get('cover_url')
        video_url=request.POST.get('video_url')
        video=Course(title=title,cover_url=cover_url,video_url=video_url)
        video.save()

        print(video)
        # if form.is_valid():
        return json_response(errmsg="课程添加成功")
        # else:
        #     return json_response(errmsg="课程添加失败")


    # permission_required = ('myadmin.course_add',)
    # model = Course
    # page_header = '在线课堂'
    # page_option = '课程管理'
    # table_title = '课程添加'
    #
    # fields = ['title', 'category', 'teacher', 'profile', 'outline', 'duration', 'cover_url', 'video_url']

class CoursesManageView(View):
    def get(self, request):
        courses = Course.objects.order_by('title')
        is_pass= request.GET.get('is_pass')
        print(is_pass)
        query_dict={}
        if is_pass:
            query_dict['is_pass']=is_pass
        else:
            pass
        course=courses.filter(**query_dict)
        print(course)
        return render(request, 'myadmin/course/courses_manage.html', context={
            "course":course
        })


    def put(self,request,course_id):
        course = Course.objects.only('id').filter(id=course_id).first()
        if course:
            course.is_pass = True
            course.save(update_fields=['is_pass'])
            return json_response(errmsg='课程审核通过')
        else:
            return json_response(errno=Code.PARAMERR, errmsg='审核的课程不存在')


class CourseIndexView(View):

    def get(self,request):
        courses =Course.objects.select_related('teacher','category').only('title','category__name','teacher__name').filter(is_delete=False)
        return render(request,'myadmin/course/course_manage.html')
#

class LessonList(View):
    def get(self,request):
        lesson_list=CourseLesson.objects.only('name')
        return render(request,'myadmin/course/lesson_list.html',context={
            'lesson_list':lesson_list
        })
    def delete(self,request,id):
        lesson= CourseLesson.objects.filter(id=id)
        if lesson:
            lesson.delete()
            return json_response(errmsg="课程删除成功")
        else:
            return json_response(errmsg="不存在")

class LessonUpdateView(UpdateView):
    permission_required = ('myadmin.lesson_update',)
    model = CourseLesson
    page_header = '课件管理'
    page_option = '课件管理'
    table_title = '课件管理'

    fields = ['name','category']

class CourseBagList(MyListView):
    """
    课件包列表
    """
    # permission_required = ('myadmin.course_list',)
    model = CourseBag
    fields = ['name','title']
    # model = Course
    # fields = ['category']
    page_header = '课件包列表'
    page_option = '课件包管理'
    table_title = '课件包列表'



class CourseBagAdd(AddView):
    # permission_required = ('myadmin.course_add',)
    model = CourseBag
    page_header = '课件包管理'
    page_option = '课件包添加'
    table_title = '课件包添加'
    fields = ['name']

# class CourseBagUpdate(UpdateView):
#     # permission_required = ('myadmin.lesson_update',)
#     model = CourseBag
#     page_header = '课件包管理'
#     page_option = '课件包管理'
#     table_title = '课件包管理'
#
#     fields = ['name','coursecategory_id']
class CourseBagUpdate(View):
    """
    课件包添加课程
    """

    def get(self,request,id,**kwargs):
        coursecate = CourseBag.objects.filter(id=id).first()


        coursebag=CourseCategory.objects.filter(coursebag__id=id)
        categorylist=CourseCategory.objects.only('name','id')

        aa = request.GET.get('category')
        print(aa)
        if aa:
            dd = CourseBag.objects.get(id=id)
            bb=CourseCategory.objects.get(id=aa)
            print(dd)
            print(bb)
            dd.w.add(bb)



        return render(request, 'myadmin/coursebag/coursebag_detail.html',context={
            'coursebag':coursebag,
            'categorylist':categorylist,
            'id':id,})




class Coursebagnameadd(View):
    """
    添加课件包名字
    """
    def get(self,request):
        return render(request,'myadmin/coursebag/coursebag_add.html')
    def post(self,request):
        name= request.POST.get('name')
        print(name)
        coursebag=CourseBag.objects.filter(name=name)
        if coursebag:
            return json_response(errmsg="已经存在该用户")
        else:
            New=CourseBag(name=name)
            New.save()
            return json_response(errmsg="成功")

class Play(View):
    def get(self,request):
        return render(request,'myadmin/course/play.html')

class CategoryList(View):
    def get(self,request):
        category= CourseCategory.objects.filter(parent=None)
        # print(category)
        categorys = []
        for obj in category:
            categorys.append(obj)
            child=obj.children.all()
            # if len(child)>0:
            #     categorys.append(CategoryList(child))
            print(categorys)


        return render(request,'myadmin/coursecategorytype/category_list.html',context={
            'categorys':categorys
        })
